# -*- coding: utf-8 -*-
"""
    api 功能函数
    查询操作等函数
"""
import json
import hashlib
import time

from flask import jsonify, current_app, Response


def api_ok(data=None):
    return jsonify({
        'code': 0,
        'data': data or {}
    })


def api_error(code=1, msg='', detail=''):
    return jsonify({
        'code': code,
        'error': current_app.config['errcode'].get(str(code), {'msg': msg, 'detail': detail})
    })


def wrap_response(data):
    return Response(
        json.dumps(data),
        status=200,
        mimetype='application/json'
    )


def wrapper_signature(data):
    """
    文档中有2种签名算法，我们需要用的是第2种
    http://gitlab.breadtrip.com:1280/piglei/breadtripserver/wikis/api-request-sign
    http://gitlab.breadtrip.com:1280/shenzhen/vacation_travel_service/wikis/breadtrip-signature
    """

    data.update({
        "secretkey": "6232bd0a603e11e5a07d60f81db103aa",
        "timestamp": int(time.time()),
        "signtype": "MD5",
        "noncestr": "noncestr",
    })

    if 'image' in data:
        del data['image']

    pre_list = []
    for key in sorted(data.keys()):
        pre_list.append('%s=%s' % (key, data.get(key)))

    pre_string = '&'.join(pre_list)
    signature = hashlib.md5(pre_string).hexdigest()
    data['signature'] = signature
    del data["secretkey"]
    # print 'wrapper_signature',  data

    return data
